
const mqtt = require('mqtt')
const host = '49.7.210.126'
const port = '1883'
const clientId = `mqtt_${Math.random().toString(16).slice(3)}`

// connect options
const OPTIONS = {
  clientId,
  clean: true,
  connectTimeout: 4000,
  username: 'admin',
  password: '@CF206cf206159!',
  reconnectPeriod: 1000,
}
let connectUrl = `mqtt://${host}:${port}`
const topic = 'mqtt'
const serverSocket = mqtt.connect(connectUrl, OPTIONS)
//监听服务器开启
serverSocket.on('connect', () => {
  console.log('服务器已连接')
  serverSocket.subscribe([topic + '/test_server'], () => {
    console.log(`已订阅'${topic}'`)
  })
})

serverSocket.on('error', (err) => {
  console.log('error: ', err)
})

//监听客户端发送的数据
serverSocket.on('message', (topic, payload) => {
  let data = payload.toString();
  console.log('cloudcontrol publish', data);
  data = JSON.parse(data).command
  publisher.publish({data})
})

serverSocket.sendData = function (data) {
  data = data || ''
  return new Promise((resolve) => serverSocket.publish(topic + '/test_client', data, { qos: 1, retain: false }, (error) => {
    if (error) {
      console.error(error)
    }
    resolve();
  }))
}

var ROSLIB = require('roslib');

var ros = new ROSLIB.Ros({
    url : 'ws://localhost:9090'
});

ros.on('connection', function() {
console.log('Connected to websocket server.');
});

ros.on('error', function(error) {
console.log('Error connecting to websocket server: ', error);
});

ros.on('close', function() {
console.log('Connection to websocket server closed.');
});

var publisher = new ROSLIB.Topic({
  ros : ros,
  name : '/cloudcontrol_publish',
  messageType : 'std_msgs/String'
});


var listener = new ROSLIB.Topic({
  ros : ros,
  name : '/cloudcontrol_listen',
  messageType : 'std_msgs/String'
});

// Then we add a callback to be called every time a message is published on this topic.
listener.subscribe(function(message) {
  console.log('cloudcontrol listen ' + message.data);
  let data = {data: message.data, type: 'info'}
  serverSocket.sendData(JSON.stringify(data))
});
